跳到主要内容

122 买卖股票的最佳时机 II

https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2zsx1/

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/

cost: 2m10s

class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) {
return 0;
}
int r = 0;
for (int i=1;i<prices.size();i++) {
if (prices[i] > prices[i-1]) {
r += prices[i] - prices[i-1];
}
}
return r;
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)